
using AutoMapper;
using DTO;
using Microsoft.AspNetCore.Mvc;
using Model;
using SqlSugar;
using Util;

namespace API.Controllers
{
    public class Base_RoleController : BaseController
    {
        Repository<tBase_Role> _Base_Role;
        Repository<tBase_RoleAction> _Role_Action;
        Repository<tBase_Action> _Base_Action;
        Repository<tBase_UserRole> _UserRole;
        Repository<tBase_User> _User; //用户表>
        readonly IMapper _mapper;
        public Base_RoleController(Repository<tBase_Role> Base_Role, IMapper mapper, Repository<tBase_RoleAction> role_Action, Repository<tBase_Action> base_Action, Repository<tBase_UserRole> userRole, Repository<tBase_User> user)
        {
            _Base_Role = Base_Role;
            _mapper = mapper;
            _Role_Action = role_Action;
            _Base_Action = base_Action;
            _UserRole = userRole;
            _User = user;
        }
        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResultMsg<string>> Save([FromBody] SaveBase_RoleInput dto)
        {
            ResultMsg<string> result = new ResultMsg<string>();
            try
               {
                 var model = _mapper.Map<tBase_Role>(dto);
                InitEntity(model);
                await _Base_Role.InsertOrUpdateAsync(model);

                //保存角色权限
                await _Role_Action.DeleteAsync(x => x.FRoleId == model.Id);
                tBase_RoleAction roleActionModel = new tBase_RoleAction();
                foreach (var item in dto.Permissions)
                {
                    roleActionModel= new tBase_RoleAction();
                    roleActionModel.FRoleId = model.Id;
                    roleActionModel.FActionId = item.id;
                    roleActionModel.FDeleted = false;
                    InitEntity(roleActionModel);
                    await _Role_Action.InsertAsync(roleActionModel);
                }
                return result.Success();
            }
            catch (Exception ex)
            {
                Util.NLOG.LogHelper.Error("Base_RoleController--Save:" + ex.ToString());
                return result.Error(ex.ToString());
            }
        }

        /// <summary>
        /// 获取列表
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResultMsg<List<Base_RoleOutput>>> GetList([FromBody] Base_RoleListInput dto)
        {
             ResultMsg<List<Base_RoleOutput>> result = new ResultMsg<List<Base_RoleOutput>>();
            try
             {
                if (dto.PageNum <= 0)
                {
                    return result.Error("PageNum不能小于或等于0");
                }
                if (dto.PageSize <= 0)
                {
                    return result.Error("PageSize不能小于或等于0");
                }
                SqlSugar.PageModel pageModel = new SqlSugar.PageModel
                {
                    PageIndex = dto.PageNum,
                    PageSize = dto.PageSize,
                };
                var exp = Expressionable.Create<tBase_Role>();
                if (!string.IsNullOrWhiteSpace(dto.RoleName))
                {
                    exp.And(x => x.FRoleName.Contains(dto.RoleName));
                }
                if (dto.Deleted != null)
                {
                    exp.And(x => x.FDeleted.Equals(dto.Deleted));
                }

                //var list = _Base_Role.GetList(exp.ToExpression());
                var list = (await _Base_Role.GetPageListAsync(exp.ToExpression(), pageModel)).OrderByDescending(x => x.CreateTime).ToList();
                var Base_RoleOutputs = _mapper.Map<List<Base_RoleOutput>>(list);
                return result.Success(Base_RoleOutputs, pageModel.TotalCount);
            }
            catch (Exception ex)
            {
                Util.NLOG.LogHelper.Error("Base_RoleController--GetList:" + ex.ToString());
                return result.Error(ex.ToString());
            }
        }
        /// <summary>
        /// 获取唯一
        /// </summary>
        /// <param name="id">主键ID</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ResultMsg<Base_RoleOutput>> GetTheOne(string id)
        {
            ResultMsg<Base_RoleOutput> result = new ResultMsg<Base_RoleOutput>();
            try
            {
                var model = await _Base_Role.GetByIdAsync(id);
                var dao = _mapper.Map<Base_RoleOutput>(model);
                var list = (await _Role_Action.GetListAsync(t => t.FRoleId == id && !t.FDeleted)).Select(c => new PermissionsInfo
                {
                    id = c.FActionId,
                }).ToList();
                foreach (var item in list)
                {
                    item.label= (await _Base_Action.GetByIdAsync(item.id))?.FName;
                }
                dao.Permissions = list;
                return result.Success(dao);
            }
            catch (Exception ex)
            {
                Util.NLOG.LogHelper.Error("Base_RoleController--GetTheOne:" + ex.ToString());
                return result.Error(ex.ToString());
            }
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id">主键ID</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ResultMsg<string>> Del(string id)
        {
            ResultMsg<string> result = new ResultMsg<string>();
            try
            {
                var model = await _Base_Role.GetByIdAsync(id);
                model.FDeleted = true;
                await _Base_Role.UpdateAsync(model);
                return result.Success();
            }
            catch (Exception ex)
            {
                Util.NLOG.LogHelper.Error("Base_RoleController--Del:" + ex.ToString());
                return result.Error(ex.ToString());
            }
        }

        /// <summary>
        /// 获取用户权限
        /// </summary>
        /// <param name="id">主键ID</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ResultMsg<List<GetMenuTreeOutput>>> GetUserMenu()
        {
            ResultMsg<List<GetMenuTreeOutput>> result = new ResultMsg<List<GetMenuTreeOutput>>();
            try
            {
                var userId = (await _User.GetFirstAsync(t => t.FUserId == CurrentUserId)).Id;
                var roleList = await _UserRole.GetListAsync(t => t.FUserId == userId);
                var actionList= await _Role_Action.GetListAsync(t=>roleList.Select(x => x.FRoleId).ToList().Contains(t.FRoleId));
                var menuList = await _Base_Action.GetListAsync(t => actionList.Select(x => x.FActionId).ToList().Contains(t.Id));
                string parentId = "0";

                // 分类处理
                var menuPageList = menuList.Select(x => new GetMenuTreeOutput
                {
                    Id = x.Id,
                    Name = x.FName,
                    ParentId = x.FParentId,
                    Type = x.FType,
                    Url = x.FUrl,
                    Value = x.FValue,
                    NeedAction = x.FNeedAction,
                    Icon = x.FIcon,
                    Sort = x.FSort,
                    Actions = new List<string>()
                }).ToList();
                // 构建树结构
                var treeList = TreeHelper.BuildTree(menuPageList, parentId);
                return result.Success(treeList);
            }
            catch (Exception ex)
            {
                Util.NLOG.LogHelper.Error("Base_RoleController--GetUserMenu:" + ex.ToString());
                return result.Error(ex.ToString());
            }
        }
    }
}
